package com.letoy.edu.service.Impl;


import com.letoy.edu.entity.User;
import com.letoy.edu.service.UserService;
import com.letoy.edu.service.auth.AuthUser;
import com.letoy.edu.utils.BCryptPasswordEncoderUtil;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 要实现UserDetailsService接口，这个接口是security提供的
 */
@Service
public class AuthUserDetailsServiceImpl implements UserDetailsService {


    @Resource
    UserService userService;
    @Resource
    BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;

    /**
     * 通过账号查找用户、角色的信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByName(username);
        System.out.println(user.getRoles());
        user.setState(0);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        } else {
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//            for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(user.getRoles()));
//            }
            return new AuthUser(user.getEmail(), user.getName(), "", user.getUserId(), user.getPassword(), 0, authorities);
        }
    }


}
